#include <tinx/fifo.h>
#include <tinx/string.h>

static int next_pos(int len, int pos)
{
    return (pos + 1) % len;
}

void fifo_init(fifo_t *fifo, char *buf, int len)
{
    fifo->len = len;
    fifo->buf = buf;
    fifo->read_ptr = 0;
    fifo->write_ptr = 0;

    memset(fifo->buf, 0, len);
}

bool fifo_full(fifo_t *fifo)
{
    return next_pos(fifo->len, fifo->write_ptr) == fifo->read_ptr;
}

bool fifo_empty(fifo_t *fifo)
{
    return fifo->read_ptr == fifo->write_ptr;
}

void fifo_put(fifo_t *fifo, char value)
{
    if (fifo_full(fifo)) 
    {
        return;
    }
    fifo->buf[fifo->write_ptr] = value;
    fifo->write_ptr = next_pos(fifo->len, fifo->write_ptr);
}

char fifo_get(fifo_t *fifo)
{
    char data = fifo->buf[fifo->read_ptr];
    fifo->read_ptr = next_pos(fifo->len, fifo->read_ptr);
    return data;
}